package cn.itsource.pethome.user.interceptor;

import cn.itsource.pethome.basic.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 响应之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //获取请求头
        String header = request.getHeader("U-TOKEN");
        //判断请求头是否为空
        if (StringUtils.isEmpty(header)) {
            //响应一个json字符串
            writeJson(response,0);
            //进行拦截
            return false;
        }
        //通过请求头token获取user的json字符串
        String userJsonStr = RedisUtils.INSTANCE.get(header);
        if (userJsonStr == null) {

            //响应一个json字符串
            writeJson(response,1);
            //进行拦截
            return false;
        }


        //重新给对象设置30分钟过期
        RedisUtils.INSTANCE.set(header, userJsonStr, 60 * 30);
        //进行放行
        return true;
    }
    /**
     * 响应一个json字符串
     * @param response
     */
    private void writeJson(HttpServletResponse response,Integer state){
    PrintWriter writer = null;
    try {
        //设置响应格式
        response.setContentType("text/json;charset=utf-8");
        //获取打印输出流
        writer = response.getWriter();
        //响应一个json字符串,如果查询到的header为空，我们传递一个转态到前台，清空前台localStorage
        //设置转态为0是前台没有token，设置为1是后台redis  token 过期
        writer.write("{\"success\":false,\"msg\":\"noUser\",\"state\":"+ state +"}");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //不为空，关闭打印流
        if (writer != null) {
            writer.close();
        }
    }
}



}
